<template>
  <view class="upload-container" @click="chooseImage">
    <!-- 显示已上传的图片 -->
    <image
      v-if="imageUrl"
      :src="imageUrl"
      class="uploaded-image"
      mode="aspectFill"
    ></image>

    <!-- 默认上传状态 -->
    <view v-else class="upload-content">
      <view class="upload-icon">
		  <uni-icons type="plus-filled" size="50" color="#42b983"></uni-icons>
	  </view>
      <text class="upload-text">点击添加图片(1920*540)</text>
    </view>

    <!-- 上传进度条 -->
    <view v-if="showProgress" class="progress-container">
      <view class="progress-bar" :style="{ width: progressPercent + '%' }"></view>
      <text class="progress-text">{{ progressPercent }}%</text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ImageUploader',
  data() {
    return {
      imageUrl: '', // 图片路径
      showProgress: false, // 是否显示进度条
      progressPercent: 0 // 上传进度百分比
    };
  },
  props:{
	url:{
		type:String,
		default:''
	}  
  },
  watch:{
	"url"(val){
		this.imageUrl = val;
	}  
  },
  methods: {
    chooseImage() {
      var that = this;
      uni.chooseImage({
        count: 1, // 只选择一张
        sizeType: ['compressed'], // 可选压缩图
        sourceType: ['album', 'camera'], // 相册或相机
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          const tempFiles = res.tempFiles[0];
          const fileName = that.generateUUIDFilename(tempFiles.name);
          
          // 重置并显示进度条
          that.showProgress = true;
          that.progressPercent = 0;
          
          uniCloud.uploadFile({
            filePath: tempFilePath,
            cloudPath: fileName,
            onUploadProgress: function(progressEvent) {
              console.log(progressEvent);
              var percentCompleted = Math.round(
                (progressEvent.loaded * 100) / progressEvent.total
              );
              // 更新进度条
              that.progressPercent = percentCompleted;
            },
            success(uploadRes) {
              that.imageUrl = uploadRes.fileID;
              that.$emit('success', uploadRes);
              // 上传成功后隐藏进度条
              setTimeout(() => {
                that.showProgress = false;
              }, 500);
            },
            fail(err) {
              uni.showToast({
                title: '图片上传失败',
                icon: 'none'
              });
              // 上传失败后隐藏进度条
              that.showProgress = false;
              that.progressPercent = 0;
			  this.$emit('fail',err);
            }
          });
        },
        fail: (err) => {
          if (!err.cancelled) {
            uni.showToast({
              title: '选择图片失败',
              icon: 'none'
            });
          }
        }
      });
    },

    uuidv4() {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },

    generateUUIDFilename(filename) {
      const ext = filename.substring(filename.lastIndexOf('.'));
      return this.uuidv4() + ext;
    }

  }
};
</script>

<style scoped>
.upload-container {
  width: 100%;
  aspect-ratio: 3.5 / 1; /* 宽高比 3.5:1，自动计算高度 */
  border: 2rpx dashed #ccc;
  border-radius: 16rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: 28rpx;
  cursor: pointer;
}

.upload-icon {
  font-size: 60rpx;
  margin-bottom: 16rpx;
  color: #1aad19;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 16rpx;
}

/* 进度条样式 */
.progress-container {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 20rpx;
  background-color: rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
}

.progress-bar {
  height: 100%;
  background-color: #1aad19;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  right: 10rpx;
  font-size: 20rpx;
  color: #333;
  font-weight: bold;
}
</style>
